import os
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'
os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
# 屏蔽 Windows symlink 警告
os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
err=r'''
Enter your token (input will not be visible):
Add token as git credential? (Y/n) n
urllib3.exceptions.SSLError: EOF occurred in violation of protocol (_ssl.c:997)

The above exception was the direct cause of the following exception:

urllib3.exceptions.ProxyError: ('Unable to connect to proxy', SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)')))

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\pro\IT\Python\flaskPy\flaskvenv\lib\site-packages\requests\adapters.py", line 644, in send
    resp = conn.urlopen(
  File "C:\pro\IT\Python\flaskPy\flaskvenv\lib\site-packages\urllib3\connectionpool.py", line 841, in urlopen
    retries = retries.increment(
  File "C:\pro\IT\Python\flaskPy\flaskvenv\lib\site-packages\urllib3\util\retry.py", line 519, in increment
    raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='huggingface.co', port=443): Max retries exceeded with url: /api/whoami-v2 (Caused by ProxyError('Unable to connect to proxy', SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)'))))

During handling of the above exception, another exception occurred:
'''

class TranslatorZH_EN_JA:
    def __init__(self):
        # 模型路径或名称
        self.model_zh_en_name = "Helsinki-NLP/opus-mt-zh-en"
        self.model_en_ja_name = "Helsinki-NLP/opus-mt-en-ja"

        # 加载中文->英文模型
        self.tokenizer_zh_en = AutoTokenizer.from_pretrained(self.model_zh_en_name)
        self.model_zh_en = AutoModelForSeq2SeqLM.from_pretrained(self.model_zh_en_name)

        # 加载英文->日语模型
        self.tokenizer_en_ja = AutoTokenizer.from_pretrained(self.model_en_ja_name)
        self.model_en_ja = AutoModelForSeq2SeqLM.from_pretrained(self.model_en_ja_name)

    def zh_to_en(self, text: str) -> str:
        """中文翻译成英文"""
        inputs = self.tokenizer_zh_en(text, return_tensors="pt")
        outputs = self.model_zh_en.generate(**inputs, max_length=200)
        return self.tokenizer_zh_en.decode(outputs[0], skip_special_tokens=True)

    def en_to_ja(self, text: str) -> str:
        """英文翻译成日语"""
        inputs = self.tokenizer_en_ja(text, return_tensors="pt")
        outputs = self.model_en_ja.generate(**inputs, max_length=200)
        return self.tokenizer_en_ja.decode(outputs[0], skip_special_tokens=True)


# ===== 测试 =====
translator = TranslatorZH_EN_JA()

# 中文 -> 英文
zh_text = "逆时针是逆着时间流动的运动？"
en_text = translator.zh_to_en(zh_text)
print("中文:", zh_text)
print("翻译成英文:", en_text)

# # 英文 -> 日语
# ja_text = translator.en_to_ja(en_text)
# print("翻译成日语:", ja_text)
